package dbLayer;

import java.sql.*;

public class DBConnection {

		private static final String driver = "jdbc:sqlserver://localhost:62584";
		private static final String databaseName = ";databaseName=Swagulator";
		
		private static String username = "; user=sa";
		private static String password = ";password=masterkey";
		
		private DatabaseMetaData dma;
		private static Connection con;
		
		private static DBConnection instance = null;
		
		private DBConnection()
		{
			String url = driver + databaseName + username + password;
			
			try
				{
				Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
				System.out.println("Load class ok");
				
			    } // end try
			catch(Exception e)
				{
				System.out.println("Can not find the driver, error: " + e);
				
				} // end catch
			try 
				{
				con = DriverManager.getConnection(url);
				con.setAutoCommit(true);
				dma = con.getMetaData();
				System.out.println("Connection to " + dma.getURL());
	            System.out.println("Driver " + dma.getDriverName());
	            System.out.println("Database product name " + dma.getDatabaseProductName());
	        }//end try
	        catch(Exception e){

	            System.out.println("Problems with the connection to the database");
	            System.out.println(e.getMessage());
	            System.out.println(url);
	        }// end catch
				
		}//end contructor
		
		public static void closeConnection()
		{
			try{
				con.close();
				System.out.println("The connection is closed");
				}
			catch (Exception e)
			{
				System.out.println("Error trying to close the database " + e.getMessage());
			}
		} // end closeDB
		
		public Connection getDBcon()
		{
			return con;
		} 
		
		public static DBConnection getInstance()
		{
			if(instance == null)
			{
				instance = new DBConnection();
				
			} // end if
			return instance;
		}
		
		public static void startTransaction()
		{
			try
			{
				con.setAutoCommit(false);
				
			} // end try
			catch(Exception e)
			{
				System.out.println("Transaction start has failed");
				System.out.println(e.getMessage());
			} // end catch
		}
		
		
		public static void commitTransaction()
			    { try{
			        con.setAutoCommit(true);
			        }
			      catch(Exception e){
			        System.out.println("commit transactio failedn");
			        System.out.println(e.getMessage());
			      }
			    }
		
		 public static void rollbackTransaction()
			    { try{
			        con.rollback();
			        con.setAutoCommit(true);
			        }
			      catch(Exception e){
			        System.out.println("rollback transaction failed");
			        System.out.println(e.getMessage());
			      }
			    }
		
		
}
